import { wsApi } from '@app-base/server';
import { useAsyncEffect, useMap } from 'ahooks';
import { Button, Checkbox } from 'antd';
import React, { useRef, useMemo } from 'react';
import BracketImagesSlide from './bracket-images-slide';
import { filterOptionsMap, getEffectiveType } from './filter-config';

interface CheckboxGroupProps {
  label: string;
  field: string;
  options: Array<string | number>;
  selected: string[];
  onChange: (field: string, value: string[]) => void;
}

const CheckboxGroup: React.FC<CheckboxGroupProps> = ({
  label,
  field,
  options,
  selected,
  onChange,
}) => (
  <div className='mb-4'>
    <h4 className='font-bold mb-1'>{label}</h4>
    <Checkbox.Group
      options={options}
      value={selected}
      onChange={(checked) => onChange(field, checked as string[])}
    />
  </div>
);

interface FilterSidebarProps {
  selectedRow: SupportFilterFields.BracketInfoMeta;
  onSearchCondition: (formInfo: Record<string, string[]>) => void;
}

// 工具函数：比较两个 map 是否相等
const isEqualMap = (a: Map<string, string[]>, b: Map<string, string[]>) => {
  if (a.size !== b.size) return false;
  for (const [key, val] of a.entries()) {
    const otherVal = b.get(key);
    if (
      !otherVal ||
      val.length !== otherVal.length ||
      !val.every((v) => otherVal.includes(v))
    ) {
      return false;
    }
  }
  return true;
};

const FilterSidebar: React.FC<FilterSidebarProps> = ({
  onSearchCondition,
  selectedRow,
}) => {
  const [filters, { set, reset, setAll }] = useMap<string, string[]>();
  const initialFiltersRef = useRef<Map<string, string[]>>(new Map());

  useAsyncEffect(async () => {
    if (selectedRow?.clamp) {
      const res = await wsApi.execAiCmd({
        c: 'GetSearchCondition',
        name: selectedRow.clamp,
      });
      const defaultValues = new Map<string, string[]>(
        Object.entries(res || {}),
      );
      setAll(Array.from(defaultValues.entries()));
      initialFiltersRef.current = defaultValues;
      onSearchCondition(Object.fromEntries(defaultValues));
    }
  }, [selectedRow]);

  const handleFilterChange = (field: string, value: string[]) => {
    // if (field === 'type') setAll([]);
    set(field, value);
  };

  const onReset = () => {
    reset();
    setAll(Array.from(initialFiltersRef.current.entries()));
  };

  const isResetDisabled = useMemo(() => {
    return isEqualMap(filters, initialFiltersRef.current);
  }, [filters]);

  const selectedTypes = filters.get('type') || [];
  const effectiveType = getEffectiveType(selectedTypes);
  const dynamicOptions = effectiveType ? filterOptionsMap[effectiveType] : null;

  return (
    <div className='w-[200px] border-r'>
      <BracketImagesSlide />
      <div
        key={filters.size}
        className='max-h-[400px] overflow-y-auto mb-4'
      >
        <CheckboxGroup
          label='型式'
          field='type'
          options={['L', 'Z']}
          selected={selectedTypes}
          onChange={handleFilterChange}
        />

        {dynamicOptions && (
          <>
            <CheckboxGroup
              label='厚度'
              field='thickness'
              options={dynamicOptions.thickness}
              selected={filters.get('thickness') || []}
              onChange={handleFilterChange}
            />
            <CheckboxGroup
              label='L1'
              field='l1'
              options={dynamicOptions.l1}
              selected={filters.get('l1') || []}
              onChange={handleFilterChange}
            />
            <CheckboxGroup
              label='L2'
              field='l2'
              options={dynamicOptions.l2}
              selected={filters.get('l2') || []}
              onChange={handleFilterChange}
            />
            <CheckboxGroup
              label='L3'
              field='l3'
              options={dynamicOptions.l3}
              selected={filters.get('l3') || []}
              onChange={handleFilterChange}
            />
            <CheckboxGroup
              label='孔数'
              field='hole'
              options={dynamicOptions.hole}
              selected={filters.get('hole') || []}
              onChange={handleFilterChange}
            />
          </>
        )}
      </div>

      <div className='flex justify-between px-2'>
        <Button
          onClick={onReset}
          disabled={isResetDisabled}
        >
          恢复
        </Button>
        <Button
          type='primary'
          onClick={() => {
            onSearchCondition(Object.fromEntries(filters));
          }}
        >
          筛选
        </Button>
      </div>
    </div>
  );
};

export default FilterSidebar;
